//
//  MapView.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/9/10.
//

import SwiftUI
import MapKit
import Combine
import JZLocationConverterSwift


struct MapView: View {
  @ObservedObject var locationManager = LocationManager.shared
  @ObservedObject var config : MapConfig
  @ObservedObject var vm = ViewModel.shared
  @State var trackingMode = MapUserTrackingMode.follow
  @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: Constants.defaultLatitude, longitude: Constants.defaultLatitude), span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))

  @State var service: WebSocketService

  @Binding var showCallTaxiView : Bool

  let timer = Timer.publish(every: 10, on: .main, in: .common).autoconnect()

  var body: some View {
    ZStack {
      Map(coordinateRegion: $config.region,
          interactionModes: .all,
          showsUserLocation: true,
          userTrackingMode: $trackingMode,
          annotationItems: config.annotationItems
      ) {
        item in
        MapAnnotation(coordinate: item.coordinate) {
          ZStack {
            Image("taxi_icon")
              .resizable()
              .scaledToFit()
              .frame(width: 64,height: 64)
              .onTapGesture(count: 1, perform: {
                vm.car = item.car
                self.showCallTaxiView = true
              })
          }
        }
      }
      .ignoresSafeArea(edges: .bottom)

      VStack {
        HStack {
          Button {
            print("return to current location")
            JZLocationConverter.default.wgs84ToGcj02(locationManager.lastLocation!.coordinate) { location in
              DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                config.region = MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))
              }
            }

          } label: {
            Image(systemName: "location.fill")
          }
          .frame(width: 5,height: 5)
          .padding()
          .background(Color(hex: "99ffffff"))
          .cornerRadius(5)

          Spacer()

          Text("经度：\(config.region.center.longitude )")
            .padding()
            .accentColor(.white)

          Text("纬度：\(config.region.center.latitude )")
            .padding()
            .accentColor(.white)

        }.padding(.leading,5)

        Spacer()
      }.onReceive(timer) { _ in
        let order = CarOrder.shared
        if service.orderState == .waiting || service.orderState  == .running {
          if let pos = locationManager.lastLocation {
            print("发送客户端位置Send Client Pos......")
            var newPos = CLLocationCoordinate2D()
            newPos.latitude = pos.coordinate.latitude + Double.randomDistance()
            newPos.longitude = pos.coordinate.longitude + Double.randomDistance()
            print("send position:\(newPos)")
            service.sendPosition(orderId: order.orderId, driverId: order.driverId, pos: newPos)
          }
        }
      }
    }
  }
}

struct MapView_Previews: PreviewProvider {
  static var previews: some View {
    MapView(config: MapConfig.shared,service: WebSocketService.shared, showCallTaxiView: .constant(true))
  }
}
